//
//  FmdbController.m
//  OCDemo
//
//  Created by BH on 15/10/30.
//  Copyright © 2015年 baohan. All rights reserved.
//

#import "FmdbController.h"
#import "LVModal.h"
#import "LVFmdbTool.h"

@interface FmdbController ()<UITableViewDataSource,UITableViewDelegate>
{
    NSMutableArray *modelAry;
}

@property (weak, nonatomic) IBOutlet UITextField *nameF;
@property (weak, nonatomic) IBOutlet UITextField *ageF;
@property (weak, nonatomic) IBOutlet UITextField *noF;
@property (weak, nonatomic) IBOutlet UITableView *table;

@end

@implementation FmdbController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    modelAry = [NSMutableArray array];
    //页面初始化时读取数据
    [self queryData:nil];
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *docDir = [paths objectAtIndex:0];
    NSLog(@"%@",docDir);
}

- (IBAction)addData:(id)sender {
    
    if (_nameF.text.length == 0 || _ageF.text.length == 0 || _noF.text.length == 0) {
        return;
    }
    
    LVModal *model = [LVModal modalWith:_nameF.text age:[_ageF.text intValue] no:_noF.text];
    BOOL isInsert = [LVFmdbTool insertModal:model];
    
    if (isInsert) {
        [modelAry addObject:model];
        [self.table reloadData];
    }else{
    
        NSLog(@"插入数据失败");
    }
    
}

- (IBAction)queryData:(id)sender {
    
    [modelAry removeAllObjects];
    
    NSString *sql;
    if (sender == nil || _noF.text.length == 0) {
        sql = nil;
    }else{
    
        sql = [NSString stringWithFormat:@"SELECT * FROM t_modals WHERE ID_No = '%@'",_noF.text];
    }
    
    //如果sql为空默认为查询表中所有数据
    NSArray *queryAry = [LVFmdbTool queryData:sql];
    [modelAry addObjectsFromArray:queryAry];
    
    [self.table reloadData];
}

- (IBAction)updateData:(id)sender {
    
    NSString *sql;
    
    [LVFmdbTool modifyData:[NSString stringWithFormat:@"UPDATE t_modals SET name='%@',age='%ld',ID_No='%@' WHERE id = '2'",_nameF.text,[_ageF.text integerValue],_noF.text]];
    
    //删除数据后执行一次查询工作刷新表格
    [self queryData:nil];
}

-(void)deleteData
{
    [LVFmdbTool deleteData:nil];
    
    [self queryData:nil];
}

#pragma mark - tableview datasource & delegate
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return modelAry.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:identifier];
    }
    
    LVModal *model = modelAry[indexPath.row];
    cell.textLabel.text = model.name;
    cell.detailTextLabel.text = model.ID_No;
    
    return cell;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}


@end
